<template>
  <div class="p-2">
    <el-card shadow="never" v-show="showSearch">
      <el-form
        :model="queryParamsBO"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="新闻标题" prop="title">
          <el-input
            v-model="queryParamsBO.title"
            placeholder="请输入新闻标题"
            clearable
          />
        </el-form-item>

        <el-form-item label="新闻类别" prop="email">
          <el-select
            v-model="queryParamsBO.articleType"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectArr.newsTypeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="发布时间" prop="createTime">
          <!-- <el-input v-model="queryParams.time" placeholder="请输入注册时间" clearable @keyup.enter="handleQuery" /> -->
          <el-date-picker
            v-model="queryParamsBO.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            查询
          </el-button>

          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <div class="p-2">
    <el-card shadow="never">
      <!-- 按钮区 -->
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Edit"
              @click="handleAdd()"
              v-hasPermi="['system:user:edit']"
            >
              新增文章
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEditNews()"
              v-hasPermi="['system:user:edit']"
            >
              编辑
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="info"-->
          <!--              plain-->
          <!--              icon="Delete"-->
          <!--              v-hasPermi="['system:user:import']"-->
          <!--              >导入</el-button-->
          <!--            >-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="info"-->
          <!--              plain-->
          <!--              icon="Delete"-->
          <!--              v-hasPermi="['system:user:export']"-->
          <!--              >导出</el-button-->
          <!--            >-->
          <!--          </el-col>-->
          <!-- <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo:export']">导出</el-button>
            </el-col> -->
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getNewsList"
          ></right-toolbar>
        </el-row>
      </template>

      <el-table :data="newsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="知识名称"
          align="center"
          prop="title"
          v-if="true"
        />

        <el-table-column label="创建者" align="center" prop="createBy" />

        <el-table-column label="状态" prop="status">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag
              :type="CommonStatusStyleTypeMap.get(row.status ?? '') ?? 'info'"
              >{{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEditNews(scope.row)"
                v-hasPermi="['system:user:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParamsBO.pageNum"
        v-model:limit="queryParamsBO.pageSize"
        @pagination="getNewsList"
      />
    </el-card>

    <!-- 新建、编辑新闻 -->
    <el-dialog
      v-model="dialogStatus.visible"
      :title="dialogStatus.title"
      width="80%"
      center
      append-to-body
      :show-close="true"
      @close="handleCloseDialog"
    >
      <el-form
        :model="dialogData"
        ref="diologFormRef"
        :inline="true"
        label-width="70px"
        class="dialogForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="name">
              <el-input
                v-model="dialogData.title"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="详细类别" prop="introduction">
              <el-select
                v-model="dialogData.articleType"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="详细类别"
              >
                <el-option
                  v-for="item in selectArr.newsTypeArr"
                  :key="(item as any).value"
                  :label="(item as any).label"
                  :value="(item as any).value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="是否置顶"
              prop="introduction"
              :disabled="dialogStatus.isDisabled"
            >
              <el-select
                v-model="dialogData.isTop"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="是否置顶"
              >
                <el-option
                  v-for="item in selectArr.isTopArr"
                  :key="(item as any).value"
                  :label="(item as any).label"
                  :value="(item as any).value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="新闻封面">
            <el-upload
              :disabled="dialogStatus.isDisabled"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handChange"
              ref="coverUpload"
            >
              <el-icon v-show="upload">
                <Plus />
              </el-icon>

              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleUpload1()"
                    >
                      <el-icon><Download /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>

            <el-dialog v-model="dialogStatus.preview">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="文章摘要" prop="introduction">
              <div class="flex" style="flex: 1">
                <el-input
                  v-model="dialogData.introduction"
                  :disabled="dialogStatus.isDisabled"
                  maxlength="256"
                  placeholder="请输入摘要"
                  rows="4"
                  type="textarea"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="页面内容" prop="status">
              <div style="border: 1px solid #ccc" v-loading="editorLoading">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :disabled="dialogStatus.isDisabled"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                />
                <editor
                  style="height: 400px; overflow-y: hidden"
                  v-model="dialogData.content"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button type="primary" icon="Check" @click="dialogSubmit">
          提交
        </el-button>
        <el-button icon="Close" @click="handleCloseDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  getOssAuth as getOssAuthApi,
  postToOSS as postToOSSApi,
  addSchoolNews as addSchoolNewsApi,
  getSchoolNewsList as getSchoolNewsListApi,
  getSchoolNewsDetail as getSchoolNewsDetailApi,
  updateSchoolNews as updateSchoolNewsApi,
  deleteSchoolNews as deleteSchoolNewsApi,
} from "@/service/api/school/news";

import type { UploadFile } from "element-plus";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { Plus, Download, ZoomIn } from "@element-plus/icons-vue";
import { SchoolSiteArticleVo } from "@/service/api/school/news/types.ts";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import {
  CommonStatusMap,
  CommonStatusStyleTypeMap,
} from "@/maps/commonMaps.ts";
import { IToolbarConfig } from "@wangeditor/editor";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const handleCreated = (editor: any) => {
  editorRef.value = editor;
  console.log("created", editor);
};

// 富文本编辑器工具栏配置
const toolbarConfig: IToolbarConfig = {
  excludeKeys: ["group-video", "fullScreen"],
};
// 配置editor
const editorConfig = {
  placeholder: "请输入新闻内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: {},
    },
  },
};

// 知识列表
const newsList = ref<SchoolSiteArticleVo[]>([]);
const total = ref(0);
const diologFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
// 获取凭证BO
const getOssAuthBO = reactive({
  originalFileName: "",
});
// 上传图片到OSSBO
const initUploadImgBO = {
  OSSAccessKeyId: "",
  callback: "",
  expire: "",
  host: "",
  policy: "",
  signature: "",
  key: "",
};
// 获取知识列表BO
const initQueryParams = {
  id: "",
  status: "",
  pageSize: 10,
  pageNum: 1,
  title: "",
  sendTime: "",
  content: "",
  cover: "",
  introduction: "",
  isTop: false,
  siteType: "",
  articleType: "",
  url: "",
  isRich: false,
  timeRange: [null, null],
  orderByColumn: "createTime",
  orderType: "desc",
};
const initDialogStatus = {
  isDisabled: false,
  preview: false,
  visible: false,
  title: "",
};

const initDialogData: SchoolSiteArticleVo = {
  id: "",
  status: "",
  title: "",
  createTime: undefined,
  content: "",
  cover: "",
  introduction: "",
  isTop: false,
  articleType: "",
  contentType: "",
};
//
const BO = reactive({
  uploadImgBO: { ...initUploadImgBO },
  queryParamsBO: { ...initQueryParams },
  dialogData: { ...initDialogData },
  dialogStatus: { ...initDialogStatus },
});
const { uploadImgBO, queryParamsBO, dialogData, dialogStatus } = toRefs(BO);

// 选择框
const selectArr = ref({
  siteTypeArr: [
    {
      value: "1",
      label: "家校共育",
    },
    {
      value: "2",
      label: "家校动态",
    },
  ],
  newsTypeArr: [
    {
      value: "0",
      label: "理念介绍",
    },
    {
      value: "1",
      label: "政策解读",
    },
    {
      value: "2",
      label: "热点新闻",
    },
    {
      value: "3",
      label: "共育活动",
    },
  ],
  isTopArr: [
    {
      value: true,
      label: "是",
    },
    {
      value: false,
      label: "否",
    },
  ],
});

/**
 * 获取新闻列表
 */
const getNewsList = async (): Promise<boolean> => {
  let [err, res] = await to<BasePageResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsListApi(queryParamsBO.value),
  );

  if (!err) {
    newsList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    newsList.value.forEach((item) => {
      item.statusMsg = CommonStatusMap.get(item.status ?? "") ?? "未知";
    });

    return true;
  }
  return false;
};

const editorLoading = ref<boolean>(false);

const single = ref(true);
const ids = ref([]);
const multiple = ref(true);
const showSearch = ref(true);

// upload ref
const coverUpload = ref();
// 上传的文件
const uploadFile = ref();
// 展示图片
const dialogImageUrl = ref("");
// 是否上传封面
const isUploadCover = ref(false);

/**
 * 选择文件改变时调用
 * @param File
 */
const handChange = (File: any) => {
  console.log(File);
  uploadFile.value = File;
};

// 封面图片上传
const handleUpload1 = async () => {
  getOssAuthBO.originalFileName = (uploadFile.value as any).name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", uploadImgBO.value.key);
  formData.append("OSSAccessKeyId", uploadImgBO.value.OSSAccessKeyId);
  formData.append("policy", uploadImgBO.value.policy);
  formData.append("signature", uploadImgBO.value.signature);
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", uploadImgBO.value.callback);
  formData.append("file", uploadFile.value.raw); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  if (res.status === 200) {
    if (res.data.code === 200) {
      queryParamsBO.value.url = res.data.data.url;
      console.log(queryParamsBO.value.url);
      isUploadCover.value = true;
    }
    ElMessage({
      type: "success",
      message: "上传成功",
    });
  }
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogStatus.value.preview = true;
};

// 超出一个文件时调用
const handleExceed: UploadProps["onExceed"] = (files) => {
  // 手动加入一个文件
  console.log(uploadFile.value);
  coverUpload.value!.handleStart(uploadFile.value);
  // 清除文件
  coverUpload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  coverUpload.value!.handleStart(file);
};

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 获取学校新闻详情
 * @param id
 */
const getSchoolNewsDetail = async (id: string): Promise<boolean> => {
  let [err, res] = await to<BaseResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsDetailApi(id),
  );
  if (!err) {
    dialogData.value = res?.data ?? initDialogData;

    return true;
  }
  return false;
};

/**
 * 处理详情按钮
 * @param row
 */
const handleDetail = async (row: any) => {
  const response = await getSchoolNewsDetail(row.id);

  if (response) {
    dialogStatus.value.title = "学校新闻详情";
    editorRef.value && editorRef.value.disable();
    dialogStatus.value.isDisabled = true;
    dialogStatus.value.visible = true;
  }
};

/**
 * 编辑按钮
 * @param row
 */
const handleEditNews = async (row?: any) => {
  const id = row?.id ?? ids.value[0];
  const response = await getSchoolNewsDetail(id);
  if (response) {
    dialogStatus.value.isDisabled = false;
    editorRef.value && editorRef.value.enable();
    dialogStatus.value.title = "编辑学校新闻";
    dialogStatus.value.isDisabled = false;
    dialogStatus.value.visible = true;
  }
};

/**
 * 处理新增按钮
 */
const handleAdd = () => {
  dialogStatus.value.title = "新增学校新闻";
  dialogStatus.value.visible = true;
};

/**
 * 处理删除按钮
 * @param row
 */
const handleDelete = async (row?: any) => {
  // 询问确认删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确认删除新闻，删除后将不可恢复", "警告", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const _ids = row?.id ?? ids.value;

    await to<BaseResponse<any>, any>(deleteSchoolNewsApi(_ids));
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getNewsList();
  }
};

/**
 * 获取上传凭证
 */
const getOssAuth = async () => {
  const res = await getOssAuthApi(getOssAuthBO);
  uploadImgBO.value = res;
  console.log(res);
};

// 获取图片base64
const getBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgResult = reader.result;
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
};

// 上传到oss
const upload = async (file: File) => {
  getOssAuthBO.originalFileName = file.name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", uploadImgBO.value.key);
  formData.append("OSSAccessKeyId", uploadImgBO.value.OSSAccessKeyId);
  formData.append("policy", uploadImgBO.value.policy);
  formData.append("signature", uploadImgBO.value.signature);
  formData.append("callback", uploadImgBO.value.callback);
  formData.append("file", file); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  return res;
};

// 自定义上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义上传
  async customUpload(file: File, insertFn: any) {
    // file 即选中的文件
    // const res = await upload(file);
    // console.log(res);
    // if (res.data.code === 200) {
    //   // 自己实现上传，并得到图片 url alt href
    //   // 最后插入图片
    //   insertFn(res.data.data.url);
    // } else {
    //   ElMessage({
    //     type: "error",
    //     message: "失败",
    //   });
    // }
    const res = await getBase64(file);
    console.log(res);
    insertFn(res);
  },
};

/**
 * 处理关闭dialog
 */
const handleCloseDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
  queryParamsBO.value = Object.assign({}, initQueryParams);
  dialogData.value = Object.assign({}, initDialogData);
  editorRef?.value?.clear();
  dialogStatus.value.isDisabled = false;
};

/**
 * 处理提交按钮
 */
const dialogSubmit = async () => {
  diologFormRef.value.validate(async (vilid: boolean) => {
    if (vilid) {
      // 编辑
      if (queryParamsBO.value.id) {
        const [err] = await to<BaseResponse<any>, any>(
          updateSchoolNewsApi(queryParamsBO.value),
        );
        if (!err) {
          ElMessage({
            type: "success",
            message: "修改成功",
          });
          getNewsList();
        }
      }
      // 新增
      else {
        const [err, res] = await to<BaseResponse<any>, any>(
          addSchoolNewsApi(queryParamsBO.value),
        );
        console.log(res);
        if (!err) {
          ElMessage({
            type: "success",
            message: "新增成功",
          });
          dialogStatus.value.visible = false;
          getNewsList();
        }
      }
      queryParamsBO.value = Object.assign({}, initQueryParams);
      handleCloseDialog();
    }
  });
};

/**
 * 查询
 */
const handleQuery = async () => {
  getNewsList();
};

/**
 * 重置按钮
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  getNewsList();
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(() => {
  getNewsList();
});
</script>

<style scoped lang="scss">
.innerDialogFooter {
  margin: 0 0 0 830px;
}

.dialogForm {
  .el-form-item {
    width: 100%;
  }
}
</style>
